#!/usr/bin/python3
# coding=utf-8
import openai
from args import *
from flask import request, jsonify
from flask import Flask
import json
from prompts import *
from flask_cors import cross_origin

client = openai.Client(
    api_key="cannot be empty",
    base_url=f"http://{xinference_url}:{xinference_port}/v1"
)



def chat_model(prompt, model_uid=model_uid, max_tokens=512, temperature=0.001):
    response = client.chat.completions.create(
        model=model_uid,
        messages=[
            {
                "content": prompt,
                "role": "user",
            }
        ],
        max_tokens=max_tokens,
        temperature=temperature
    )
    return response.choices[0].message.content
app = Flask(__name__)
app.debug = False


@app.route('/model/extract/summary', methods=['post'])
@cross_origin()
def post_http_entities():
    req = request.get_json()
    data = req.get('data', [])
    if data == []:
        return jsonify({'error': 'no data'}), 400
    context = []
    for d in data:
        title = d.get("title", "")
        # time = d.get("time", "")
        # context.append([time, title])
        context.append(title)
    context = "|".join(context)
    context = context[:limit_len]
    prompt = get_summary_prompt(context)
    response = chat_model(prompt)
    response = replace_no_need(response)
    try:
        data = response
    except:
        return {
            "code": 200,
            "data": "",
            "message": "解析json错误"
        }
    ret = {
        "code": 200,
        "data": data,
        "message": "success"
    }
    return jsonify(ret)

@app.route('/model/chat', methods=['post'])
@cross_origin()
def post_http_chat():
    req = request.get_json()
    context = req.get('data', "")

    context = context[:limit_len]
    prompt = context
    response = chat_model(prompt)
    try:
        data = response
    except:
        return {
            "code": 200,
            "data": "",
            "message": "解析json错误"
        }
    ret = {
        "code": 200,
        "data": data,
        "message": "success"
    }
    return jsonify(ret)

def replace_no_need(response):
    response = response.replace("摘要：", "")
    response = response.replace("摘要:", "")
    response = response.replace("若需要更详细的摘要，需要更多的新闻内容进行分析。", "")
    response = response.replace("请注意，摘要内容是基于新闻标题的简洁总结，可能未完全反映出每则新闻的详细情况。", "")
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)
    # 这里指定了地址和端口号。也可以不指定地址填0.0.0.0那么就会使用本机地址ip
